package operations;

public class SpellAction{
	
	private Tree<?> tst = Loader.getTST();
	
	
	public String doAction(String textFieldContents) {
		int returnValues = 0;
		boolean[] hasValue = {false, false, false, false};
		int currentLastNum;
		long time = System.currentTimeMillis();
		tst.setMatchAlmostDiff(0);
		String[] intermediateResults = {"", "", "", ""};
		intermediateResults[0] = tst.matchAlmostString(textFieldContents);
		currentLastNum = tst.getLastNumReturnValues();
		if(currentLastNum > 0) hasValue[0] = true;
		returnValues += currentLastNum;
		tst.setMatchAlmostDiff(1);
		intermediateResults[1] = tst.matchAlmostString(textFieldContents);
		currentLastNum = tst.getLastNumReturnValues();
		if(currentLastNum > 0) hasValue[1] = true;
		returnValues += currentLastNum;
		
		Tree<Object> uniqueKeyTree;
		if(textFieldContents.length() > 3) {
			String currentResult;
			uniqueKeyTree = new Tree<Object>();
			Object keyMarker = new Object();
			String altered;
			for(int i = 0; i <= textFieldContents.length(); i++) {
				altered = textFieldContents.substring(0, i) + "*" + textFieldContents.substring(i);
				currentResult = tst.matchAlmostString(altered);
				
				if(currentResult.length() > 0) uniqueKeyTree.save(currentResult, keyMarker);
			}
			
			tst.setMatchAlmostDiff(0);
			for(int i = 0; i < textFieldContents.length(); i++) {
				textFieldContents.charAt(i);
				altered = textFieldContents.substring(0, i) + textFieldContents.substring(i + 1);
				currentResult = tst.matchAlmostString(altered);
				if(currentResult.length() > 0) uniqueKeyTree.save(currentResult, keyMarker);
			}
			intermediateResults[2] = uniqueKeyTree.sortKeysString();
			if(intermediateResults[2].length() > 0) hasValue[2] = true;
			returnValues += uniqueKeyTree.numDataNodes();
		}
		if(textFieldContents.length() > 5) {
			tst.setMatchAlmostDiff(2);
			intermediateResults[3] = tst.matchAlmostString(textFieldContents);
			currentLastNum = tst.getLastNumReturnValues();
			if(currentLastNum > 0) hasValue[3] = true;
			returnValues += currentLastNum;
		}
		String finalResult = (hasValue[0]) ? intermediateResults[0] : "";
		for(int i = 0; i < 3; i++) {
			if(hasValue[i] && hasValue[i]) finalResult += "\n";
			finalResult += intermediateResults[i+1];
		}
		time = System.currentTimeMillis() - time;
		return finalResult;
	}
}